var table = new Vue({
    el: '.ntDesktop',
    data: {
        date: [],
        year: [],
        current: {},
        list: [],
        searchText: '',//查找公司名称
        accountins: [],//支付账号
        companys: [],//公司名称
        companyacc: [],//公司账号
        Should: [],//应付款项
        contract: [],//选择合同
        page: 1,
        pageSize: 2,
        shoupage: 1,
        shoupageSize: 2,
        isshow: true,
        isshows: false,
        iftijiao: true,
        tab: true,
        order: 1,
        pauname: '',
        data: {
            happen_day: '',//发生日期
            account_id: '',//支付账号id
            co_id: '',//公司id
            bank_id: '',//公司账户
            amount: '',//金额
            remarks: '',//备注
        },
        sum: {
            Shouldsum: 0,//应付合计
            alreadysum: 0,//已付合计
            betweensum: 0//差额合计
        },
        //合同合计
        comsum: {
            withsum: 0,//应付合计
            hassum: 0//付款合计
        },
        merge: [],//合并支付
        buy_poInfo:{
            terms:{
                after_sale:{content:''},
                enter:{content:''},
                normal:{content:''},
                pay:{content:''}
            },
            content_sum:{
                name:'',
                bankname:'',
                account_name:'',
                account_num:''
            }
        },
        fin_co2buy_id:0,//流水Id
        allsel:false
    },
    //计算总的支出
    computed: {
        sumoney(){
            var s = 0;
            this.list.forEach(e => {
                s += e.amount;
            });
            return s;
        },
    },
    methods: {
        //分页
        setPage(pageCurrent, pageSum, element, lsorx,pagesize) {
            //数据总条数
            var myPageCount = pageSum;
            //一页显示多少条
            var myPageSize = pagesize;
            //总页数
            var countindex = myPageCount % myPageSize > 0 ? (myPageCount / myPageSize) + 1 : (myPageCount / myPageSize);
            $.jqPaginator(element, {
                totalPages: parseInt(countindex),
                //最多显示多少页
                visiblePages: 5,
                //默认显示第几页
                currentPage: pageCurrent,
                first: '<li class="first"><a href="javascript:;">'+langcon.page_home+'</a></li>',
                prev: '<li class="prev"><a href="javascript:;"><i class="arrow arrow2"></i>'+langcon.previous_page+'</a></li>',
                next: '<li class="next"><a href="javascript:;">'+langcon.next_page+'<i class="arrow arrow3"></i></a></li>',
                last: '<li class="last"><a href="javascript:;">'+langcon.last_page+'</a></li>',
                page: '<li class="page"><a href="javascript:;">{{page}}</a></li>',
                all:'<li class="page"><a href="javascript:;">'+parseInt(countindex)+' / '+this.page+'PG , '+pagesize+' /PG</a></li>',
                onPageChange: (num, type) => {
                    if(type=='change')
                    if (lsorx) {
                        this.shoupage = num
                        this.getdata()
                    }else {
                        if (type == "change") {
                            this.page = num
                            this.getAllList()
                        }
                    }
                }
            });
        },
        //付款流水数据获取
        getAllList(){
            $.ajax({
                url: "/admin/finance/cotwobuy",
                type: 'post',
                data: {
                    page: this.page,//分页
                    pageSize: this.pageSize,//条数
                    cotwobuy: '',
                    yearmonth: this.current.year + '-' + this.current.month,//日期
                },
                dataType: "json",
                success: (result) => {
                    this.list = result.data;
                    this.data.happen_day = result.happen_day;//发生日期
                    this.accountins = result.accountins;//支付账号
                    // 将数据渲染到页面
                    if (result.size / this.pageSize > 1) {
                        $('#pagination').show()
                        this.setPage(parseInt(this.page), result.size)
                        this.setPage(parseInt(this.page), result.size, '#pagination', 0,this.pageSize)
                    } else {
                        $('#pagination').hide()
                    }
                }
            })
        },
        //标签切换
        changepay(code){
            this.page = '1';
            if (code == 0) {
                this.tab = true
                this.getAllList()
            } else {
                this.tab = false
                this.getdata()
            }
        },
        //删除付款流水
        delcotwo(id, name, code){
            $.ajax({
                url: '/admin/finance/cotwobuydel',
                type: 'post',
                data: {
                    id,
                    name,
                    code
                },
                success: (res) => {
                    res = JSON.parse(res)
                    change_mes_type('.alert',res.status)
                    if (res.status != 1) {
                        $('.alert').show()
                        $('.alert p').html('*' + res.msg + '<br>');
                        return false;
                    } else {
                        $('.alert').show()
                        $('.alert p').html('*' + res.msg + '<br>')
                        if (!(this.list.length - 1)) {
                            if(this.page>1){
                                this.page--
                            }
                        }
                        this.getAllList();
                    }
                }
            })
        },
        //保存数据
        savefun(){
                if (this.data.id) {
                    // 编辑
                    this.data.act = 'cotwobuyedit'
                } else {
                    //添加
                    this.data.act = 'cotwobuyadd'
                }
                var data = {
                    act: this.data.act,//提交标志
                    happen_day: this.data.happen_day,//发生时间
                    id: this.data.id,//编辑id
                    account_id: this.data.account_id,//支付账号
                    co_id: this.data.co_id,//公司id
                    remarks: this.data.remarks,//备注
                    bank_id: this.data.bank_id,//公司账户
                    agreement: this.contract,//合同
                    amount: this.data.amount,//付款金额
                }
                if(this.iftijiao){
                    $.ajax({
                        url: '/admin/finance/' + this.data.act,
                        data,
                        type: 'post',
                        success: (data) => {
                            data = JSON.parse(data)
                            change_mes_type('.alert',data.status)
                            if (data.status != 1) {
                                $('.alert').show()
                                $('.alert p').html('*' + data.msg + '<br>')
                            } else {
                                console.log(data.fin_co2buy_id);
                                this.iftijiao = false;
                                //清空数据
                                $('.alert').show()
                                $('.alert p').html('*' + data.msg + '<br>')
                                this.getAllList();//获取列表数据
                                this.getdata();//待付款接口
                            }
                        }
                    })
                }

        },
        //点击编辑,请求接口，渲染数据
        editdata(id){
            this.fin_co2buy_id = id
            $.ajax({
                url: '/admin/finance/cotwobuyedit',
                data: {
                    id: id,
                    getcotwobuyedit: '',
                },
                type: 'post',
                dataType: 'json',
                success: (data) => {
                    this.data.happen_day = data.happen_day;
                    this.data.account_id = data.account_id
                    this.data.co_id = data.co_id;
                    this.data.bank_id = data.bank_id;
                    this.data.remarks=data.remarks;
                    this.companys=data.companys;//公司
                    this.data.amount=data.amount;//支付金额
                    this.changecompany();//获取账户和合同
                    this.data.id=data.id;//对公付款id
                }
            })
        },
        //点击国家，获取不同公司账户
        changecompany(){
            this.getcompanyacc();//账户
            this.getcontract()//合同
        },
        //获取公司的账户
        getcompanyacc(){
            $.ajax({
                url: "/admin/finance/cotwobuy",
                type: 'post',
                data: {
                    company_id: this.data.co_id,
                    getcompanyacc: '',
                },
                dataType: "json",
                success: (result) => {
                    this.companyacc = result;//公司账号
                }
            })
        },
        //获取合同
        getcontract(){
            if (this.fin_co2buy_id) {
                var url = "/admin/api/getBuyPoAndCompany?fin_co2buy_id="+this.fin_co2buy_id;
            }else{
                var url = "/admin/api/getBuyPo";
            }
            $.ajax({
                url: url,
                type: 'post',
                data: {
                    company_id: this.data.co_id
                },
                dataType: "json",
                success: (result) => {
                    this.contract = result
                     this.contract.forEach(element => {
                        if(element.cost_list)
                        {
                            element.cost_list.check = false
                        if (!this.fin_co2buy_id || !element.cost_list.price){
                            element.cost_list.price = 0
                        }
                        if(element.cost_list.price){
                            element.cost_list.check=true
                        }
                        }
                        element.paypoarr.forEach(item => {
                            item.check = false
                            if (!this.fin_co2buy_id || !item.price){
                                item.price = 0
                            }
                            if(item.price){
                                item.check=true
                            }
                        })
                    })
                    console.log(this.contract)
                    this.compon()
                    this.fin_co2buy_id=0
                }
            })
        },
        changedate(index, is_change){
                this.current=this.date[index]
                if (index >= 0) {
                    this.date[0] = JSON.parse(JSON.stringify(this.date[index]))
                    this.current = JSON.parse(JSON.stringify(this.date[0]))
                    var time = JSON.parse(JSON.stringify(this.date[0]))
                } else {
                    var time = JSON.parse(JSON.stringify(this.date[0]))
                    if (time.month + 1 == 13) {
                        time.year++
                        time.splyear++
                        time.month = 1
                    } else {
                        time.month++
                    }
                    this.date[0] = JSON.parse(JSON.stringify(time))
                    this.current = JSON.parse(JSON.stringify(this.date[0]))
                }
                for (var i = 1; i < 6; i++) {
                    if (time.month - 1 == 0) {
                        time.year--
                        time.splyear--
                        time.month = 12
                    } else {
                        time.month--
                    }
                    this.date.splice(i, 1, JSON.parse(JSON.stringify(time)))
                }
                if (this.tab)
                this.getAllList()
            else
                this.getdata()
        },
        //查找公司
        search(){
            $.ajax({
                url: "/admin/finance/cotwobuy",
                type: 'post',
                data: {
                    dname: this.searchText,
                    getcompanyname: ''
                },
                dataType: "json",
                success: (result) => {
                    this.companys = result;
                }
            })
        },
        //获取应付款项
        getdata(){
            $.ajax({
                url: '/admin/api/getBuyPo_pain',
                type: 'post',
                data: {
                    date: this.current,
                    page: this.shoupage,
                    limit: this.shoupageSize
                },
                success: (date) => {
                    this.sum.Shouldsum=0
                    this.sum.alreadysum=0
                    this.sum.betweensum=0
                    var datearr = JSON.parse(date)
                    this.Should = datearr.list
                    for (const key in this.Should) {
                        this.Should[key].forEach(element => {
                            this.sum.Shouldsum += element.cost_sum + element.price_sum
                            this.sum.alreadysum += element.paid_sum
                            //this.sum.Shouldsum+=element.price_sum
                        });
                    }
                    if (datearr.page.size / this.shoupageSize > 1) {
                        $('#pagshowination').show()
                        this.setPage(datearr.page.page - 0,datearr.page.size-0, '#pagshowination',1,this.shoupageSize)
                    } else {
                        $('#pagshowination').hide()
                    }
                    this.sum.betweensum += this.sum.Shouldsum - this.sum.alreadysum

                }
            })
        },
        //付款
        payfun(element, childen, is_cost){
            element = JSON.parse(JSON.stringify(element))
            this.searchText=element.company_name;
            this.search();//搜索公司
            this.data.co_id=element.company_id;
            this.getcompanyacc();//获取公司的账户
            childen = JSON.parse(JSON.stringify(childen))
            childen.price = 0
            childen.check=true
            childen.amount -= childen.paid
            if (!this.contract.some(item => {
                    if (item.id == element.id) {
                        if (is_cost) {
                            item.cost_list = childen
                        } else {
                            if (!item.paypoarr.some(data => {
                                    return data.id == childen.id
                                })) {
                                item.paypoarr.push(childen)
                            }
                        }
                    }
                    return item.id == element.id
                }) || this.contract.length == 0) {
                if (is_cost) {
                    element.paypoarr = []
                    element.cost_list = childen
                } else {
                    element.paypoarr = [childen]
                    element.cost_list = {}
                }
                this.contract.push(element)
            }
            this.$nextTick(function(){
                this.seltedfun(true)
            })
            this.compon()
        },
        //勾选
        banck(element, childen, is_cost, e){
            if ($(e.target).prop('checked')) {
                this.merge.push({
                    element,
                    childen,
                    is_cost
                })
            } else {
                this.merge.forEach((element, index) => {
                    if (element.childen.id == childen.id) {
                        this.merge.splice(index, 1)
                    }
                })
            }
        },
        //合并支付
        mergepay(){
            this.merge.forEach(element => {
                this.payfun(element.element, element.childen, element.is_cost)
            })
        },
        //计算总和
        compon(){
            this.comsum.withsum=0
            this.comsum.hassum=0
            this.contract.forEach(element=>{
                if( element.cost_list)
                if(element.cost_list.amount!=undefined && element.cost_list.paid!=undefined){
                    this.comsum.withsum+=element.cost_list.amount
                    this.comsum.hassum+=(element.cost_list.price-0)
                }
                element.paypoarr.forEach(item=>{
                    this.comsum.withsum+=(item.amount-0)
                    this.comsum.hassum+=(item.price-0)
                })
            })
        },
        // 获取合同详情
        getBuyPoInfo(id){
            $.ajax({
                url:'/admin/api/getBuyPoInfo?po_id='+id,
                type:'post',
                data:{data:this.contract},
                success:(data)=>{
                    data=JSON.parse(data)
                    this.buy_poInfo = data
                }
            }) 
        },
        allche(e){    //选择合同 全选
            if($(e.target).prop('checked')){
                this.contract.forEach((element,index)=>{
                    this.$set(this.contract[index].cost_list, 'check', true);
                    element.paypoarr.forEach((item,key)=>{
                        this.$set(this.contract[index].paypoarr[key], 'check', true);
                    })
                })
            }else{
                this.contract.forEach((element,index)=>{
                    this.$set(this.contract[index].cost_list, 'check', false);
                    element.paypoarr.forEach((item,key)=>{
                        this.$set(this.contract[index].paypoarr[key], 'check', false);
                    })
                })
            }
            this.$forceUpdate();
        },
        seltedfun(e){
            if(e){
                if(this.contract.every(element=>{
                    if(JSON.stringify(element.cost_list) != "{}" && !element.cost_list.check){
                            return false
                        }
                        return element.paypoarr.every(item=>{
                            return item.check
                        })
                    })){
                        this.allsel=true
                    }
            }else{
                this.allsel=false
            }
        },
        sortoneData(a, b) {
            if (this.order == 1) {
                $(event.target).attr('data-order', 2)
                return b[this.pauname] - a[this.pauname]
            } else {
                $(event.target).attr('data-order', 1)
                return a[this.pauname] - b[this.pauname]
            }
        },
        //排序
        sortfun(type, $event){  //排序
            this.order = $(event.target).attr('data-order')
            if (type == 1) {
                this.pauname = 'happen_day'
                this.list.sort(this.sortoneData);
            }
            if (type == 2) {
                this.pauname = 'amount'
                this.list.sort(this.sortoneData);
            }
            if (type == 3) {
                this.pauname = 'update_at'
                this.list.sort(this.sortoneData);
            }
        }
    },
    mounted(){
        var date = new Date()
        var time = {
            year: date.getFullYear(),
            splyear: date.getFullYear().toString().slice(2, 4) - 0,
            month: date.getMonth() + 1
        }
        this.year[0] = date.getFullYear()
        this.date[0] = JSON.parse(JSON.stringify(time))
        this.current = this.date[0]
        this.changedate(0,false)
        this.getAllList();//获取付款流水列表数据
        this.getdata();//获取应付款项
        $('.form_datetime').on('changeDate', (e)=>{
            this.data.happen_day=this.$refs.fkdate.value
        });
    }
})
$("#pay_detailModal").on("hidden.bs.modal", function () {
    $(this).removeData("bs.modal");
    $(document).unbind('keydown')
});